

import UIKit
import GradientLoadingBar
import Alamofire
import Reachability
import SwiftEventBus


class FavoriteRoleViewController: UIViewController {
    let cell_identifier:String = "recommendRoleCell"
    var list:[Role] = []
    let reachability = try! Reachability()
    var myNavigationController: UINavigationController?
    // 懒加载
    lazy var tableView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        let itemW = (UIScreen.main.bounds.width - 32)/2
        layout.itemSize = CGSize(width: itemW, height: itemW*2.3/4)
        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        
        layout.scrollDirection = .vertical // 竖向滑动
        
        let tableView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = commonBackgroundColor
        tableView.register(CustomRoleCell.self, forCellWithReuseIdentifier: cell_identifier)
        
        return tableView
    }()
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.black]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "收藏"
        self.view.addSubview(tableView)
        
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.view).offset(32)
            make.bottom.equalTo(self.view).offset(-60)
            make.width.equalTo(self.view)
        }
        
        
        let createRoleButton = UIButton(type: .custom)
        createRoleButton.setTitle("创建角色", for: .normal)
        createRoleButton.layer.cornerRadius = 21
        createRoleButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        createRoleButton.frame.size = CGSize(width: UIScreen.main.bounds.width/3, height: 20)
        createRoleButton.backgroundColor = .primaryColor
        createRoleButton.addTarget(self, action: #selector(createRole(_:)), for: .touchUpInside)
        self.view.addSubview(createRoleButton)
        createRoleButton.snp.makeConstraints { make in
            make.right.equalTo(self.view.snp.centerX).offset(-12)
            make.bottom.equalTo(self.bottomLayoutGuide.snp.top).offset(-12)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width/3)
        }
        
        let favoriteRoleButton = UIButton(type: .custom)
        favoriteRoleButton.setTitle("添加收藏", for: .normal)
        favoriteRoleButton.layer.cornerRadius = 21
        favoriteRoleButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        favoriteRoleButton.frame.size = CGSize(width: UIScreen.main.bounds.width/3, height: 20)
        favoriteRoleButton.backgroundColor = .primaryColor
        favoriteRoleButton.addTarget(self, action: #selector(favoriteRole(_:)), for: .touchUpInside)
        self.view.addSubview(favoriteRoleButton)
        favoriteRoleButton.snp.makeConstraints { make in
            make.left.equalTo(self.view.snp.centerX).offset(12)
            make.bottom.equalTo(self.bottomLayoutGuide.snp.top).offset(-12)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width/3)
        }
        
        
        reachability.whenReachable = { reachability in
            if reachability.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
            
            
            self.getLocalJson()
            self.getRecommendRoleList()
            self.getAllRoleList()
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_DELETE_ROLE) { result in
            if let result = result{
                
                let alertController = UIAlertController(title: "提示",
                                                        message: "确定要删除此角色吗？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "删除", style: .default, handler: {
                    action in
                    let deleteRole : Role = result.object as! Role
                    var index = 0
                    for role in self.list{
                        if role.title == deleteRole.title && role.description == deleteRole.description{
                            break
                        }
                        index = index + 1
                    }
                    self.list.remove(at: index)
                    self.tableView.reloadData()
                    self.updateLocalJson()
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
                
            }
            
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_ADD_ROLE) { result in
            if let result = result{
                let addRole : Role = result.object as! Role
                if self.isExist(addRole){
                    self.view.makeToast("已添加",position: .center)
                }else{
                    self.list.append(addRole)
                    self.tableView.reloadData()
                    self.updateLocalJson()
                }
                
            }
            
        }
        
    }
    
    func isExist(_ role: Role) -> Bool{
        var  exist = false
        for item in list{
            if item.title == role.title{
                exist = true
                break
            }
        }
        
        return exist
    }
    
    func updateLocalJson(){
        do {
            var roleResponse = RoleResponse(code: 200, data: self.list, message: "success")
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(roleResponse)
            let json = String(data: jsonData, encoding: String.Encoding.utf8)
            if let jsonString = json{
                StoreManager.setRecommendRoleJson(json: jsonString)
            }
        } catch {
            print(error)
        }
    }
    
    @objc private func createRole(_ sender: Any) {
        
        let detailViewController = CreateRoleViewController()
        detailViewController.pageTitle = "创建角色"
        
        myNavigationController?.pushViewController(detailViewController, animated: true)
        
        print("handleRightBarButtonTapped")
    }
    
    
    @objc private func favoriteRole(_ sender: Any) {
        
        let detailViewController = AssistantTabViewController()
        detailViewController.pageTitle = "点击添加"
        detailViewController.isFavorite = true
        detailViewController.myNavigationController = myNavigationController
        myNavigationController?.pushViewController(detailViewController, animated: true)
        
        print("handleRightBarButtonTapped")
    }
    
    
    
    func getLocalJson(){
        self.parseJson(json: StoreManager.getRecommendRoleJson())
        
    }
    
    
    //只拉取数据保存
    func getAllRoleList(){
        let parameters = BasicParameters()
        AFManager.sharedInstance.manager.request("\(baseUrl)diy_ai/listV2",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            
            if let string = response.value{
                print(string)
                StoreManager.setAllRoleJson(json: string)
            }
        }
        
    }
    
    func getRecommendRoleList(){
        let parameters = BasicBidParameters(bid: StoreManager.getBid())
        AFManager.sharedInstance.manager.request("\(baseUrl)personal_helper/getRecommendByBid",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            
            if let string = response.value , !string.contains("[]"){
                print(string)
                                self.parseJson(json: string)
                StoreManager.setRecommendRoleJson(json: string)
            }
        }
        
    }
    
    func parseJson(json: String){
        
        let data = Data(json.utf8)
        do {
            let jsonDecoder = JSONDecoder()
            let roleResponse = try jsonDecoder.decode(RoleResponse.self, from: data)
            if !roleResponse.data.isEmpty{
                
                list = roleResponse.data
                self.tableView.reloadData()
            }
            
            
        } catch {
            
            print(error.localizedDescription)
        }
        
    }
    
}

extension FavoriteRoleViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cell_identifier, for: indexPath) as! CustomRoleCell
        cell.bindViewModel(role:list[indexPath.row])
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item + 1)
        let chatViewController = AdvancedExampleViewController()
                let role = list[indexPath.row]
                chatViewController.roleDescription = role.description
                chatViewController.pageTitle = role.title
                chatViewController.rolePrompt = role.prompt
                chatViewController.inputHint = role.title
                chatViewController.type = 1
        //        chatViewController.example = ""
        //        chatViewController.exampleAnswer = role.description
        myNavigationController?.pushViewController(chatViewController, animated: true)
    }
    
}
